package com.sxw.hw_student.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxw.hw_student.system.entity.SysUserRole;
import com.sxw.hw_student.system.service.ISysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/userRole")
public class SysUserRoleController {

    @Autowired
    private ISysUserRoleService service;

    @GetMapping("/list")
    public List<SysUserRole> list(@RequestParam(required = false) String search) {
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        if (search != null && !search.isEmpty()) {
            try {
                Long longVal = Long.parseLong(search);  // 这里用 Long 适配 roleId
                wrapper.and(w -> w.eq("user_id", longVal).or().eq("role_id", longVal));
            } catch (NumberFormatException e) {
                // 输入不是数字，返回空列表
                return List.of();
            }
        }
        return service.list(wrapper);
    }

    @PutMapping("/update")
    public void update(@RequestBody SysUserRole role) {
        service.updateById(role);
    }

    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable int id) {
        service.removeById(id);
    }
}
